<?php
namespace App\Http\Controllers\admin_system;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use DB;


class EditController extends Controller{

    public function index(Request $request)
    {
        $id             = $request->input('articleId',0);
        if($id > 0)
        {
            $articleInfo = DB::table('articles')->where('articleId',$id)->first();
        }else{
            $articleInfo = new \stdClass();
            $articleInfo->articleId = 0;
            $articleInfo->content   = "";
            $articleInfo->title     = "";
            $articleInfo->thumb_img = "";
            $articleInfo->img       = "";
            $articleInfo->desc      = "";
        }

        return view('admin_system/edit/edit',['articleInfo'=>$articleInfo]);
    }


    /**
     * 保存内容
     * */
    public function save(Request $request)
    {

        $articleId      = $request->input('articleId',0);

        $data   = [
            'title'     => $request->input('title'),
            'content'   => $request->input('content'),
            'updated_at'=> date_time(),
            'desc'      => $request->input('desc',''),
            'thumb_img' => $request->input('thumbImg',''),
            'img'       => $request->input('img',''),
        ];

        if($articleId > 0)
        {
            DB::table('articles')->where('articleId',$articleId)->update($data);

        }else{

            $data['created_at']     = date_time();
            $articleId              = DB::table('articles')->insertGetId($data);
        }

        return apiData()->set_data('articleId',$articleId)->send(200,'ok');

    }


    public function saveImg()
    {

        $dir        = "uploads/".date('Y')."/".date('m')."/".date('d');
        $storyPath  = public_path($dir);

        if(!file_exists($storyPath))
        {
            //mkdir($storyPath,true);
            mk_dir($storyPath);
        }
        $images = [];
        foreach($_FILES as $key => $file)
        {
            $filename   = $file['name'];
            $extend     = pathinfo($filename);
            $type       = strtolower($extend["extension"]);
            $newFile    = time().rand(1000,9000).".".$type;

            $tempFile   = $file['tmp_name'];
            move_uploaded_file($tempFile,$storyPath."/".$newFile);
            array_push($images,"/".$dir."/".$newFile);
        }

        $data = ['errno'=>0,'data'=>$images];

        echo json_encode($data);
    }


    public function articles(Request $request)
    {
        $keywords   = $request->input('keywords');
        $articles   = DB::table('articles')->paginate(20);
        return view('admin_system/edit/articles',['articles'=>$articles,'keyword'=>$keywords]);
    }


}